package com.douyinkan.controller;

import com.douyinkan.dto.ContentDTO;
import com.douyinkan.entity.Content;
import com.douyinkan.service.ContentService;
import com.douyinkan.service.impl.ContentServiceImpl;
import com.douyinkan.util.FileUtil;
import com.douyinkan.util.MediaFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/api/contents")
public class ContentController {
    
    private static final Logger logger = LoggerFactory.getLogger(ContentController.class);
    
    @Autowired
    private ContentService contentService;

    @Autowired
    private ContentServiceImpl contentServiceImpl;
    

    @GetMapping("/parse-file-info")
    public ResponseEntity<MediaFileInfo> parseMediaFileInfo(@RequestParam String filePath) {
        logger.info("Parsing media file info for path: {}", filePath);

        try {
            MediaFileInfo fileInfo = contentServiceImpl.parseMediaFileInfo(filePath);

            if (fileInfo != null) {
                logger.info("Successfully parsed file info for: {}", filePath);
                return ResponseEntity.ok(fileInfo);
            } else {
                logger.warn("Failed to parse file info for: {}", filePath);
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            logger.error("Error parsing file info for: {}", filePath, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/{id}/file")
    public ResponseEntity<Resource> getContentFile(@PathVariable Long id) {
        logger.info("Getting file for content id: {}", id);
        ContentDTO content = contentService.getContentById(id);
        if (content == null) {
            logger.warn("Content not found with id: {} when trying to access file", id);
            return ResponseEntity.notFound().build();
        }
        
        File file = new File(content.getFilePath());
        if (!file.exists()) {
            logger.warn("File not found at path: {} for content id: {}", content.getFilePath(), id);
            return ResponseEntity.notFound().build();
        }
        
        try {
            Resource resource = new FileSystemResource(file);
            String contentType = determineContentType(content.getFilePath());
            
            logger.info("Successfully retrieved file: {} for content id: {}, content type: {}", 
                       file.getName(), id, contentType);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getName() + "\"")
                    .contentLength(file.length())
                    .body(resource);
        } catch (Exception e) {
            logger.error("Error retrieving file for content id: {}", id, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    private String determineContentType(String filePath) {
        String extension = FileUtil.getFileExtension(filePath);
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            case "mp4":
                return "video/mp4";
            case "avi":
                return "video/x-msvideo";
            case "mov":
                return "video/quicktime";
            case "mkv":
                return "video/x-matroska";
            case "webm":
                return "video/webm";
            case "flv":
                return "video/x-flv";
            case "wmv":
                return "video/x-ms-wmv";
            case "m4v":
                return "video/x-m4v";
            default:
                return "application/octet-stream";
        }
    }
    
    // 内部类用于处理请求体
    public static class RatingRequest {
        private Integer rating;
        
        public Integer getRating() {
            return rating;
        }
        
        public void setRating(Integer rating) {
            this.rating = rating;
        }
    }
    
    public static class TagRequest {
        private Long tagId;
        
        public Long getTagId() {
            return tagId;
        }
        
        public void setTagId(Long tagId) {
            this.tagId = tagId;
        }
    }
}